package com.easy.commons.utils.http;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.easy.commons.utils.http.handler.DefaultResulthandler;
import com.easy.commons.utils.http.handler.InputStreamResultHandler;
import org.apache.http.Consts;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import com.easy.commons.utils.http.handler.ResultHandler;

import com.alibaba.fastjson.JSONObject;

/**
 * 
 * @Title: HttpService.java
 * @Package com.trs.common.utils.http
 * @Description: HTTP_CLIENT 4.5
 * @author linNaibin
 * @date 2020年8月31日 上午9:05:58
 * @version V1.0
 */
public class HttpService {

	// 超时时间
	private final static int TIMEOUT = 5000;

	public static String httpGet(String url, ResultHandler handler) {

		CloseableHttpClient httpclient = null;
		//
		//
		CloseableHttpResponse response = null;
		try {
			httpclient = HttpClients.createDefault();
			HttpGet httpGet = new HttpGet(url);
			RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(TIMEOUT)
					.setConnectionRequestTimeout(1000).setSocketTimeout(TIMEOUT).build();
			httpGet.setConfig(requestConfig);
			response = httpclient.execute(httpGet);
			// 得到状态行
			return handler.handler(response);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			// close
			try {

				if (response != null) {
					response.close();
				}
				if (httpclient != null) {
					httpclient.close();
				}

			} catch (IOException e) {

			}

		}

	}

	public static String httpPost(String url, Map<String, String> params, ResultHandler handler) throws IOException {

		CloseableHttpClient httpclient = null;
		//
		CloseableHttpResponse response = null;

		try {
			httpclient = HttpClients.createDefault();

			HttpPost httpPost = new HttpPost(url);

			RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(TIMEOUT)
					.setConnectionRequestTimeout(1000).setSocketTimeout(TIMEOUT).build();
			httpPost.setConfig(requestConfig);

			List<NameValuePair> formParams = new ArrayList<NameValuePair>();

			if (null != params && params.size() > 0) {

				params.forEach((String k, String v) -> {
					// 表单参数
					formParams.add(new BasicNameValuePair(k, v));
				});
			}

			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, Consts.UTF_8.name());

			httpPost.setEntity(entity);

			response = httpclient.execute(httpPost);

			return handler.handler(response);

		} catch (Exception e) {

			e.printStackTrace();
			return null;
		} finally {
			// close
			try {

				if (response != null) {
					response.close();
				}
				if (httpclient != null) {
					httpclient.close();
				}

			} catch (IOException e) {

			}

		}


	}

	/**
	 * 
	 * post请求提交json参数
	 * 
	 * @throws IOException
	 * 
	 */
	public static String httpPayload(String url, JSONObject params, ResultHandler h) throws IOException {

		CloseableHttpClient httpClient = null;
		//
		CloseableHttpResponse response = null;
		try {
			httpClient = HttpClients.custom().build();

			HttpPost httpPost = new HttpPost(url);

			if (params != null) {
				StringEntity entity = new StringEntity(params.toJSONString());

				httpPost.setEntity(entity);
			}

			response = httpClient.execute(httpPost);

			return h.handler(response);

		} catch (Exception e) {
			System.out.println("报错啦！！！");
			e.printStackTrace();
			return null;
		} finally {
			// close
			try {

				if (response != null) {
					response.close();
				}
				if (httpClient != null) {
					httpClient.close();
				}

			} catch (IOException e) {

			}

		}

	}

	public static void image() {


		// https://t1.tianditu.gov.cn/cva_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL=50&TILEROW=26&TILEMATRIX=6&tk=9a02b3cdd29cd346de4df04229797710
		String TILEMATRIX = "17";

		String TILEROW = "18441";
		String TILECOL = "108243";
		String tk = "a92e641c3af7b0925c36209424482979";
		String url = "http://t1.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX=" + TILEMATRIX + "&TILEROW=" + TILEROW + "&TILECOL=" + TILECOL + "&tk=" + tk;

		httpGet(url,new InputStreamResultHandler());
	}

	public static void json () throws IOException {
		JSONObject j = new JSONObject();
		j.put("dio", "the word!");
		String result = httpPayload("http://127.0.0.1/trs-api/test/地址栏传过来的", j, new DefaultResulthandler());

		System.out.println("客户端结果:" + result);
	}

	// 知乎
	public static void answerList() {

		String url ="https://www.zhihu.com/api/v4/questions/368227698/answers?limit=20&offset=0";


		String result = httpGet(url,new DefaultResulthandler());
		System.out.println("结果: \n" + result );

		JSONObject json = JSONObject.parseObject(result);

		JSONArray array = json.getJSONArray("data") ;

		System.out.println("2");

	}
	// 知乎
	public static void answerDetail() {
// 995361241
		// 990183060
		//
		String url ="https://www.zhihu.com/api/v4/answers/1782524168?include=data[*].content";

		url ="https://account.jetbrains.com/lservice/rpc/validateKey.action";
		// url_token e0509636
		String result = httpGet(url,new DefaultResulthandler());
		System.out.println("结果: \n" + result );
	}



	
	public static void main(String[] args) throws IOException {

		//answerList();
		answerDetail();
	}
}
